import KoaRouter from 'koa-router'
import Config from '@/config/Config'
import { Models } from '@/common/typings/modle'
import regexp from '@/common/utils/regexp'
import { getEmailValidateCode, smsCodeIsOk } from '@/common/utils/utils'
import { ParameterException, Success } from '@/core/HttpException'
import path from 'path'
import { saveSmsCode } from '@/server/redis'
import { sendEmail } from '@/common/utils/email.utils'
const router = new KoaRouter({
  prefix: `${Config.API_PREFIX}v1/system/email`,
})
router.post('/send', async (ctx: Models.Ctx) => {
  // 1 验证邮箱格式合法
  // 2 验证传入的验证码正确，且未过期
  // 3 发送验证码到指定邮箱
  const { email, smsCode } = ctx.request.body as any
  if (!regexp.email.test(email)) {
    throw new ParameterException({ msg: 'email 格式不正确' })
  }
  smsCodeIsOk(ctx, smsCode)
  const validateCode = getEmailValidateCode()
  // console.log('验证码：', validateCode)
  const templatePath = path.resolve(__dirname, '@/common/constants/email/verificationTemplate.ejs')

  await sendEmail({
    templatePath,
    validateCode,
    email,
  })

  await saveSmsCode(email, validateCode)
  throw new Success()
})
export default router
